package com.qiku.service.impl;

import com.qiku.entity.LoginUser;
import com.qiku.entity.ResponseResult;
import com.qiku.entity.User;
import com.qiku.enums.AppHttpCodeEnum;
import com.qiku.exception.SystemException;
import com.qiku.service.BlogLoginService;
import com.qiku.utils.BeanCopyUtils;
import com.qiku.utils.JwtUtils;
import com.qiku.vo.UserInfoVo;
import com.qiku.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断认证是否通过
        if(Objects.isNull(authenticate)){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //获取userId的  生成token
        LoginUser loginUser = userDetailsServiceImpl.loadUserByUsername(user.getUserName());
        String userId = loginUser.getUser().getId().toString();
        //工具类获取token
        String token = JwtUtils.getJwtToken(userId,"id");
        //把用户信息存入redis
        redisTemplate.opsForValue().set("login2-"+userId, loginUser);
        //把token封装  返回
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);
        return ResponseResult.okResult(map);
    }

}
